using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.ComponentModel.Design;
using Widgetsphere.Generator.Models;

namespace Widgetsphere.Generator.Design.Editors
{
	internal class TableReferenceSingleSelectEditor : System.Drawing.Design.UITypeEditor
	{
		public TableReferenceSingleSelectEditor()
		{
		}

		public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return System.Drawing.Design.UITypeEditorEditStyle.DropDown;
		}

		System.Windows.Forms.Design.IWindowsFormsEditorService edSvc = null;
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			Reference retval = null;
			try
			{
				edSvc = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService));

				ModelRoot root = null;
				if (context.Instance is Relation)
					root = (ModelRoot)((Relation)context.Instance).Root;
				else if (context.Instance is Table)
					root = (ModelRoot)((Table)context.Instance).Root;

				TableCollection tableCollection = root.Database.Tables;

				//Create the list box 
				System.Windows.Forms.ListBox newBox = new System.Windows.Forms.ListBox();
				newBox.Click += new EventHandler(newBox_Click);
				newBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

				SortedList sortedList = new SortedList();
				foreach (Table table in tableCollection)
				{
					//Ensure key is unique to avoid error
					string text = table.Name.ToLower();
					string key = text;
					int ii = 0;
					while (sortedList.ContainsKey(key))
					{
						key = text + ii.ToString();
						ii++;
					}
					sortedList.Add(key, table);
				}

				//Re-add them in order
				foreach (DictionaryEntry di in sortedList)
					newBox.Items.Add((Table)di.Value);

				edSvc.DropDownControl(newBox);
				if ((newBox.SelectedIndex > -1) && (newBox.SelectedItem != null))
					retval = ((Table)newBox.SelectedItem).CreateRef();

			}
			catch (Exception ex) { }
			return retval;
		}

		private void newBox_Click(object sender, System.EventArgs e) 
		{ 
			if (edSvc != null)
				edSvc.CloseDropDown();
		}

	}
}
